﻿/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.IO;
using System.Collections.Generic;

using Gtk;
using Mono.Unix;

using DCSharp.Backend.Objects;

namespace DCSharp.Gui
{
	public class UploadStore : ListStore
	{
		private Dictionary<Uploader, TreeIter> uploadToIter;

		public enum Column {
			Object,
			Name,
			Path,
			SizeText,
			Size,
			Position,
			ProgressText,
			Progress,
			TimeLeft,
			User,
			Started
		};

		public UploadStore() : base(typeof(object), typeof(string),
			typeof(string), typeof(string), typeof(double), typeof(double),
			typeof(string), typeof(int), typeof(string), typeof(string),
			typeof(string))
		{
			uploadToIter = new Dictionary<Uploader, TreeIter>();
		}

		#region Methods

		public TreeIter Add(Uploader uploader)
		{
			if (uploader == null)
			{
				throw new ArgumentNullException("uploader");
			}

			TreeIter iter = AppendValues(uploader);
			SetValue(iter, (int)Column.Started, DateTime.Now.ToString());

			uploadToIter.Add(uploader, iter);

			Update(uploader);
			return iter;
		}

		public TreeIter Remove(Uploader uploader)
		{
			if (uploader == null)
			{
				throw new ArgumentNullException("uploader");
			}

			TreeIter iter = uploadToIter[uploader];
			uploadToIter.Remove(uploader);

			Remove(ref iter);
			return iter;
		}

		public void Update(Uploader uploader)
		{
			if (uploader == null)
			{
				throw new ArgumentNullException("uploader");
			}
			if (!uploadToIter.ContainsKey(uploader))
			{
				return;
			}

			TreeIter iter = uploadToIter[uploader];

			string name = GetName(uploader);
			if (uploader.Request.Type == RequestType.File)
			{
				SetValue(iter, (int)Column.Name, Path.GetFileName(name));
				SetValue(iter, (int)Column.Path, Path.GetDirectoryName(name));
			}
			else
			{
				SetValue(iter, (int)Column.Name, name);
			}

			SetValue(iter, (int)Column.Size, (double)uploader.FileSize);
			SetValue(iter, (int)Column.SizeText, Util.FormatFileSize(uploader.FileSize));
			SetValue(iter, (int)Column.User, uploader.User.Nick);

			// Get the position and length
			// TODO: Add helper properties to Uploader?
			long length;
			long position;
			double progress;

			// Handle file segment requests as if the whole file was requested
			FileRequest fileRequest = uploader.Request as FileRequest;
			if (fileRequest != null)
			{
				long count = fileRequest.Count ?? uploader.FileSize - fileRequest.Start;

				length = uploader.FileSize;
				position = fileRequest.Start + (long)(uploader.Progress * count);
				progress = (double)position/length;
			}
			else
			{
				length = uploader.FileSize;
				position = (long)(uploader.Progress * length);
				progress = uploader.Progress;
			}

			// Progress
			string progressText = String.Format(Catalog.GetString("{0} of {1}"),
				Util.FormatFileSize(position),
				Util.FormatFileSize(length));

			SetValue(iter, (int)Column.ProgressText, " " + progressText + " ");
			SetValue(iter, (int)Column.Progress, (int)(progress * 100));

			// Remaining
			string timeLeft = null;
			if (uploader.Active)
			{
				// Use the remaining time of the whole file if it's a file segment upload.
				if (fileRequest != null && fileRequest.Count + fileRequest.Start !=
					uploader.FileSize)
				{
					double bps = uploader.Connection.Monitor.UploadSpeed;
					if (bps > 0)
					{
						TimeSpan totalRemaining = TimeSpan.FromSeconds(
							(int)((uploader.FileSize - position) / bps));

						timeLeft = String.Format("≈{0}", totalRemaining);
					}
				}
				else
				{
					TimeSpan remaining = uploader.GetRemainingTime();
					timeLeft = remaining.ToString();
				}
			}

			SetValue(iter, (int)Column.TimeLeft, timeLeft);
		}

		public bool Contains(Uploader uploader)
		{
			return uploadToIter.ContainsKey(uploader);
		}

		private static string GetName(Uploader uploader)
		{
			switch (uploader.Request.Type)
			{
				case RequestType.File:
					return uploader.LocalFile.FullName;

				case RequestType.List:
					return Catalog.GetString("File list");

				case RequestType.HashTree:
					return String.Format(Catalog.GetString("Hash tree for file {0}"),
						((HashTreeRequest)uploader.Request).TTH);
			}
			throw new NotImplementedException("Unknown request type " +
				uploader.Request.Type);
		}

		#endregion
	}
}
